package model

import (
	"furni-manage/furnirpc/furnirpc"
	"gorm.io/gorm"
)

type Manage struct {
	gorm.Model
	ManageName  string  `gorm:"type:varchar(30)"`
	LogoId      int     `gorm:"type:int"`
	ManageNum   int     `gorm:"type:int"`
	ManagePrice float64 `gorm:"type:decimal(10,2)"`
	ClassId     int     `gorm:"type:int"`
}

func (m *Manage) ManageAdd(db *gorm.DB) error {
	return db.Debug().Create(m).Error
}

func (m *Manage) FindMangeByMangeName(db *gorm.DB, name string) error {
	return db.Where("manage_name=?", name).First(&m).Error
}
func FindManageList(db *gorm.DB, list []*furnirpc.ManageList, in *furnirpc.ManageListRequest) []*furnirpc.ManageList {
	/*
		SELECT
		  manage_name AS manageName,
		  class_name AS className,
		  manage_num AS manageNum,
		  logos.logo_name AS logoName,
		  manage_price AS managePrice,
		  manages.created_at
		FROM
		  manages
		  JOIN logos ON manages.logo_id = logos.id
		  JOIN classes ON manages.class_id = classes.id
	*/
	tx := db.Debug().Model(&Manage{}).Select(
		"manage_name AS manage_name",
		"classes.name AS class_name",
		"manage_num AS manage_num",
		"logos.name AS logo_name",
		"manage_price AS manage_price",
		"manages.created_at").
		Joins("JOIN logos ON manages.logo_id = logos.id").
		Joins("JOIN classes ON manages.class_id = classes.id")
	if in.ManageName != "" {
		tx.Where("manage_name like ?", "%"+in.ManageName+"%")
	}
	if in.LogoName != "" {
		tx.Where("logos.name=?", in.LogoName)
	}
	if in.StartCreatedAt != "" {
		tx.Where("classes.name <=0", in.StartCreatedAt)
	}
	if in.EndCreatedAt != "" {
		tx.Where("classes.name >=0", in.EndCreatedAt)
	}

	tx.Find(&list)
	return list
}
